﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.Model;//系统所有的model 都在这个命名空间里，这个还是比较有好处的。
using NetWing.BPM.Core;
using NetWing.Common;
using Omu.ValueInjecter;
using NetWing.Common.Data;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using static NetWing.BPM.Admin.JydModleOrder.ashx.ajax_submit;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System.Net;
using System.IO;
using Senparc.NeuChar.MessageHandlers;
using System.Text;
using NetWing.BPM.Admin.JLDD.lib;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.User;

namespace NetWing.BPM.Admin.Psi_OrderMain.ashx
{
    /// <summary>
    /// mjfinance 的摘要说明
    /// </summary>
    public class Psi_OrderMainHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
            string edNumber = common.mjcommon.getedNumber("JH");






            int mainInsertedId = 0;//（主表公用）主表插入的ID
            int fmainInsertedId = 0;//财务主表插入的ID
            //这里可以执行一些逻辑
            if (string.IsNullOrEmpty(main) || string.IsNullOrEmpty(detail))
            {
                context.Response.Write("{\"status\":0,\"msg\":\"失败！主表或子表信息为空！\"}");
                context.Response.End();//输出结束
            }

            
            #region 主表处理
            var mainobj = JSONhelper.ConvertToObject<Psi_OrderModel>(main);//根据模型把json数据转化为obj
            Psi_OrderModel mainModel = new Psi_OrderModel();//初始化主表模型
            mainModel.InjectFrom(mainobj);//把obj插入模型
            mainModel.add_time = DateTime.Now;//给主表添加时间和更新时间赋值，其他字段赋值以此类推
            mainModel.up_time = DateTime.Now;
            mainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
            mainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
            mainModel.orderType = "进货单";
            mainModel.edNumber = edNumber;
            #endregion

            #region 子表明细表处理
            JArray detailArr = JArray.Parse(detail);//把明细表转化为数组
            var k = detailArr[0].ToString();
            #endregion
            #region 数据库事务
            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {

                //重要更新：用户取消进销存与财务关联。金额默认为0


                //主要改了fmainModel.payment=0;fmainModel.total=0;

                mainInsertedId = DbUtils.tranInsert(mainModel, tran);//往主表插入一条
                #region 财务主表处理
                //财务主表处理 方便以后财务统计s
                MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
                fmainModel.account = mainModel.paybank;//账号
                fmainModel.accountid = mainModel.paybankid;//账号ID
                fmainModel.add_time = DateTime.Now;
                fmainModel.contact = mainModel.Contacts;
                fmainModel.contactid = mainModel.ContactsId;
                //fmainModel.dep = dep;//部门
                fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                fmainModel.edNumber = edNumber;
                fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                fmainModel.unit = mainModel.unit;//用户
                fmainModel.unitid = mainModel.unitid;//用户ID
                fmainModel.note = "进销存主表id:" + mainInsertedId.ToString() + mainModel.Contacts + "";
                fmainModel.payment = mainModel.shifu;
                fmainModel.total = mainModel.total;
                fmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
                fmainModel.operate = SysVisitor.Instance.cookiesUserName;
                //fmainModel.note = mainInsertedId.ToString();//把插入的ID作为note
                fmainInsertedId = DbUtils.tranInsert(fmainModel, tran);//往财务主表插入一条
                                                                       //财务主表处理 方便以后财务统计e
                #endregion
                #region 财务明细表处理
                MJFinanceDetailModel fdetailModel = new MJFinanceDetailModel();//初始化明细表模型
                fdetailModel.financeId = fmainInsertedId;//财务主表ID
                fdetailModel.ftype = "";
                fdetailModel.edNumber = edNumber;
                fdetailModel.subject = "进货";
                fdetailModel.subjectid = 39;//39是进货
                fdetailModel.sumMoney = fmainModel.total;
                fdetailModel.dep = "";
                fdetailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                fdetailModel.note = fmainModel.note;
                fdetailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                fdetailModel.add_time = DateTime.Now;
                fdetailModel.up_time = DateTime.Now;
                DbUtils.tranInsert(fdetailModel, tran);//执行写入财务明细表
                #endregion
                //循环明细表
                for (int i = 0; i < detailArr.Count; i++)//有几条就执行几次
                {
                    var detailobj = JSONhelper.ConvertToObject<Psi_BuyDetailsModel>(detailArr[i].ToString());//根据模型把明细表转化为obj
                    Psi_BuyDetailsModel detailModel = new Psi_BuyDetailsModel();//初始化明细表模型
                    detailModel.InjectFrom(detailobj);//把obj插入模型
                    detailModel.PsiOrderID = mainInsertedId;//父子表关联  养成一个习惯两表关联 字表里有 主表名+id 即主表id
                    detailModel.add_time = DateTime.Now;
                    detailModel.up_time = DateTime.Now; //每个都应该有up_time 和add_time
                    detailModel.orderType = mainModel.orderType;//单据类型
                    detailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                    detailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                    detailModel.paybank = mainModel.paybank;//付款银行
                    detailModel.paybankid = mainModel.paybankid;//付款银行id
                    detailModel.unitname = mainModel.unit;//往来单位
                    detailModel.unitid = mainModel.unitid;
                    detailModel.unit_man = mainModel.unit_man;
                    detailModel.unit_moble = mainModel.unit_moble;
                    detailModel.Contacts = mainModel.Contacts;//联系人
                    detailModel.ContactsId = mainModel.ContactsId;//
                    detailModel.profit = 0;//进货时毛利是0
                    detailModel.edNumber = edNumber;
                    detailModel.examine_status = 1; //状态是1要审核哦
                    detailModel.order_id = mainModel.aorder_id;
                    DbUtils.tranInsert(detailModel, tran);//执行写入明细表，这里写的明细表是写进出明细表，不写进货物明细表中
                                                          //循环更新库存信息，同时更新进价，因为每个时候的进价都会不一样
                    
                    //为模版中的各属性赋值
                    var templateData = new ProductTemplateData()
                    {
                        first = new TemplateDataItem("("+ SysVisitor.Instance.cookiesUserName + ")请您审核采购订单:"+mainModel.aorder_id, "#000000"),
                        keyword1 = new TemplateDataItem(detailModel.goodsName, "#000000"),
                        //keyword2 = new TemplateDataItem("总价:"+fmainModel.total.ToString()+ "元 =  数量: " + detailModel.buyNum + " * 单价:" + detailModel.buyPrice.ToString(), "#000000"),
                        keyword2 = new TemplateDataItem("总价:"+detailModel.buyAllMoney+"元 =  数量: " + detailModel.buyNum + " * 单价:" + detailModel.buyPrice.ToString(), "#000000"),
                        keyword3 = new TemplateDataItem(DateTime.Now.ToString(), "#000000"),
                        keyword4 = new TemplateDataItem(detailModel.unitname, "#000000"),
                        remark = new TemplateDataItem("请尽快审核！", "#000000")
                    };
                    string templateid = NetWing.Common.ConfigHelper.GetValue("templageid2");//从web.config 获得模板ID
                    //通知所有员工就是openid不同
                    DataTable dt = SqlEasy.ExecuteDataTable("select * from Sys_Users where openid<>'' and IsAdmin = 1");
                    string appId = ConfigHelper.GetValue("AppID");
                    string appSecret = ConfigHelper.GetValue("AppSecret");
                    foreach (DataRow ndr in dt.Rows)
                    {
                        string openid = ndr["openid"].ToString();
                        string access_token = ConfigHelper.GetValue("access");
                        int lv = 0;
                        if (string.IsNullOrEmpty(access_token))
                        {
                            if (!AccessTokenContainer.CheckRegistered(appId))//检查是否已经注册
                            {
                                AccessTokenContainer.Register(appId, appSecret);//如果没有注册则进行注册
                            }
                            access_token = AccessTokenContainer.GetAccessTokenResult(appId).access_token;
                            ConfigHelper.SetAppSetting("access", access_token);
                        }
                        if (!string.IsNullOrEmpty(access_token))
                        {
                            UserInfoJson userInfo = null;
                            try
                            {
                                userInfo = UserApi.Info(access_token, openid);
                            }
                            catch
                            {
                                userInfo = null;
                            }
                            if (userInfo != null)
                            {
                                lv = userInfo.subscribe;
                            }
                            else
                            {
                                if (!AccessTokenContainer.CheckRegistered(appId))//检查是否已经注册
                                {
                                    AccessTokenContainer.Register(appId, appSecret);//如果没有注册则进行注册
                                }
                                access_token = AccessTokenContainer.GetAccessTokenResult(appId).access_token;
                                ConfigHelper.SetAppSetting("access", access_token);
                                try
                                {
                                    userInfo = UserApi.Info(access_token, openid);//获取
                                }
                                catch
                                {
                                    userInfo = null;
                                }
                                if (userInfo != null)
                                {
                                    lv = userInfo.subscribe;
                                }
                                else
                                {
                                    lv = 0;
                                }
                            }
                        }
                        if (lv == 1)
                        {
                            string r = NetWing.BPM.Admin.weixin.wxhelper.sendTemplateMsg(openid, templateid, NetWing.Common.ConfigHelper.GetValue("website") + "JydModleOrder/viewflow.aspx", templateData);
                        }
                    }





                    //采购时要更新商品价格为+数，examine_status为1时不写进Psi_Goods数据库
                    //string stocksql = "update Psi_Goods set stock=stock+" + detailModel.buyNum + ",buyprice="+(-detailModel.buyPrice)+",up_time='"+DateTime.Now.ToString()+"' where keyid=" + detailModel.goodsId + "";
                    //DbUtils.tranExecuteNonQuery(stocksql, tran);


                }
                //循环明细表
                //事务的方法执行sql语句
                //可以写些什么逻辑放在这里
                //进货 减掉银行账户余额
                int c = DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance-" + mainModel.total + " where KeyId=" + mainModel.paybankid + "", tran);


                tran.Commit();//提交执行事务
                context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\"}");
            }
            #endregion
            catch (Exception e)
            {
                tran.Rollback();//错误！事务回滚！
                context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                throw;
            }
        }

        protected string GetJson(string url)
        {
            //访问https需加上这句话 
            // ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
            //访问http（不需要加上面那句话） 
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            wc.Encoding = Encoding.UTF8;
            string returnText = wc.DownloadString(url);

            if (returnText.Contains("errcode"))
            {
                //可能发生错误 
            }
            //Response.Write(returnText); 
            return returnText;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}